
#include <unistd.h>

#include <buf.h>
#include <event.h>
#include <log.h>

#include "server.h"
#include "client.h"

extern struct event_t *g_event;

struct server_t g_server;

int server_init(int fd)
{
	g_server.fd = fd;
	g_server.bufin = buf_create("serv in", 4096);
	g_server.bufout = buf_create("serv out", 4096);

	return 0;
}

// read from server.
int server_trans(int fd, void *arg)
{
	int n;

	g_client.lastcmd = time(NULL);

	n = buf_read(g_server.bufin, fd);
	if(n == -1) {
		LOGD("buf read return -1");
		event_stop(g_event);
	}

	LOGD("from server buf_read : %s, read from : %d", buf_data(g_server.bufout), n);

	if(n > 0) {
		event_add(g_event, STDOUT_FILENO, EVTYPE_WT, server_write, &g_server);
	}

	return n;
}

// write to client.
int server_write(int fd, void *arg)
{
	int n;

	n = buf_write(g_server.bufin, fd);
	if(n == -1) {
		LOGD("buf write return -1");
		event_stop(g_event);
	}

	if(buf_length(g_server.bufin) == 0) {
	event_del(g_event, fd, EVTYPE_WT);
	}

	LOGD("to client write : %d", n);

	return n;
}


